import json
import os
import csv
import sys
from collections import OrderedDict


class DataImportDemo:
    def __init__(self, dataClass, filePath):
        self.decodeCsv = dataClass
        self.filePath = filePath

    def get_search_keys(self, args):
        row = self.get_column_row(args)
        search_keys = self.decodeCsv.get_search_keys()
        parameterStr = ','.join(row)
        parameters = parameterStr.split(',')
        params_len = len(parameters)
        search_col = []
        for i in range(0, params_len):
            if parameters[i] in search_keys:
                search_col.append({"i": i, "n": parameters[i]})
        self.search_col = search_col
        self.search_keys = search_keys

    def print_search_keys(self, args):
        self.get_search_keys(args)
        print json.dumps(self.search_keys)

    def get_attribute_keys(self, args):
        row = self.get_column_row(args)
        attribute_keys = self.decodeCsv.get_attribute_keys()
        parameterStr = ','.join(row)
        parameters = parameterStr.split(',')
        params_len = len(parameters)
        attribute_col = []
        for i in range(0, params_len):
            if parameters[i] in attribute_keys:
                attribute_col.append({"i": i, "n": parameters[i]})
        self.attribute_col = attribute_col
        self.attribute_keys = attribute_keys

    def print_attribute_keys(self, args):
        self.get_attribute_keys(args)
        print json.dumps(self.attribute_keys)

    def get_column_names(self, args):
        generate_no = 1
        row = self.get_column_row(args)
        self.get_search_keys(args)
        self.get_attribute_keys(args)
        parameterStr = ','.join(row)
        parameters = parameterStr.split(',')
        params_len = len(parameters)
        column_col = []
        if (len(args) > 5 and (args[5] == "True")):
            for i in range(0, params_len):
                if not parameters[i] in self.search_keys:
                    if not parameters[i] in self.attribute_keys:
                        if not len(parameters[i]) == 0:
                            column_col.append({"i": i, "n": parameters[i], "validity": False})
                        elif self.decodeCsv.get_item_name_generator_flag() == True:
                            column_col.append(
                                    {"i": i, "n": ("AUTO GENERATOR NAME_" + str(generate_no)), "validity": False})
                            generate_no += 1

            exclude = args[6:]
            try:
                csvFile = file(self.filePath, 'rb')
                csvReader = csv.reader(csvFile)
                for row in csvReader:
                    break
                csvFile = file(self.filePath, 'rb')
                csvReader = csv.reader(csvFile)
            except Exception:
                csvFile = file(self.filePath, 'rU')
                csvReader = csv.reader(csvFile)
            for row in csvReader:
                line_no = csvReader.line_num
                row_result = self.decodeCsv.get_data_row(line_no, row)
                if row_result == False:
                    continue
                if row_result == True:
                    parametersStr1 = ','.join(row)
                    parameters1 = parametersStr1.split(',')
                    column_col_len = len(column_col)
                    for i in range(0, column_col_len):
                        if column_col[i]["validity"] == False:
                            if (is_number(parameters1[column_col[i]["i"]]) == True) \
                                    or (parameters1[column_col[i]["i"]] in exclude):
                                column_col[i]["validity"] = True
            csvFile.close()
        else:
            for i in range(0, params_len):
                if not len(parameters[i]) == 0:
                    column_col.append({"i": i, "n": parameters[i], "validity": True})
                elif self.decodeCsv.get_item_name_generator_flag() == True:
                    column_col.append(
                            {"i": i, "n": ("AUTO GENERATOR NAME_" + str(generate_no)), "validity": True})
                    generate_no += 1

        self.column_col = column_col

    def print_column_names(self, args):
        self.get_column_names(args)
        column_len = len(self.column_col)
        result = []
        for i in range(0, column_len):
            if self.column_col[i]["validity"] == True:
                result.append(self.column_col[i]["n"])
        print json.dumps(result)

    def get_param_keys(self, args):
        self.get_column_names(args)
        param_row = self.get_param_row(args)
        column_len = len(self.column_col)
        param_col = OrderedDict({})
        for i in range(0, column_len):
            param_col[self.column_col[i]["n"]] = param_row[0][self.column_col[i]["i"]] \
                                                 + ',' + param_row[1][self.column_col[i]["i"]] + ',' + param_row[2][
                                                     self.column_col[i]["i"]]
        self.param_col = param_col

    def print_param_keys(self, args):
        self.get_param_keys(args)
        print json.dumps(self.param_col)

    def print_data_by_names(self, args):
        self.get_column_names(args)
        self.get_search_keys(args)
        self.get_attribute_keys(args)
        target_names = []
        target_names = args[5:]
        target_col = []
        search_col_len = len(self.search_col)
        for i in range(0, search_col_len):
            target_col.append(self.search_col[i])
        attribute_col_len = len(self.attribute_col)
        for i in range(attribute_col_len):
            target_col.append(self.attribute_col[i])
        self_column_len = len(self.column_col)
        for i in range(0, self_column_len):
            if self.column_col[i]["n"] in target_names:
                target_col.append(self.column_col[i])
        target_col_len = len(target_col)
        try:
            csvFile = file(self.filePath, 'rb')
            csvReader = csv.reader(csvFile)
            for row in csvReader:
                break
            csvFile = file(self.filePath, 'rb')
            csvReader = csv.reader(csvFile)
        except Exception:
            csvFile = file(self.filePath, 'rU')
            csvReader = csv.reader(csvFile)
        for row in csvReader:
            line_no = csvReader.line_num
            row_result = self.decodeCsv.get_data_row(line_no, row)
            if row_result == True:
                data = (','.join(row)).split(',')
                data_row = OrderedDict({})
                data_len = len(data)
                for i in range(0, target_col_len):
                    data_row[target_col[i]["n"]] = data[target_col[i]["i"]]
                print json.dumps(data_row)
        csvFile.close()

    def print_all_data(self, args):
        self.get_column_names(args)
        self.get_search_keys(args)
        self.get_attribute_keys(args)
        target_col = []
        search_col_len = len(self.search_col)
        for i in range(0, search_col_len):
            target_col.append(self.search_col[i])
        attribute_col_len = len(self.attribute_col)
        for i in range(attribute_col_len):
            target_col.append(self.attribute_col[i])
        target_col += self.column_col
        target_col_len = len(target_col)
        try:
            csvFile = file(self.filePath, 'rb')
            csvReader = csv.reader(csvFile)
            for row in csvReader:
                break
            csvFile = file(self.filePath, 'rb')
            csvReader = csv.reader(csvFile)
        except Exception:
            csvFile = file(self.filePath, 'rU')
            csvReader = csv.reader(csvFile)
        data_all = []
        for row in csvReader:
            line_no = csvReader.line_num
            row_result = self.decodeCsv.get_data_row(line_no, row)
            if row_result == True:
                data = (','.join(row)).split(',')
                data_row = OrderedDict({})
                data_len = len(data)
                for i in range(0, target_col_len):
                    data_row[target_col[i]["n"]] = data[target_col[i]["i"]]
                data_all.append(data_row)
        csvFile.close()
        self.get_param_keys(args)
        print json.dumps(self.param_col)
        print json.dumps(data_all)
        print json.dumps(self.search_keys)
        print json.dumps(self.attribute_keys)
        return data_all

    def get_column_row(self, args):
        try:
            csvFile = file(self.filePath, 'rb')
            csvReader = csv.reader(csvFile)
            for row in csvReader:
                break
            csvFile = file(self.filePath, 'rb')
            csvReader = csv.reader(csvFile)
        except Exception:
            csvFile = file(self.filePath, 'rU')
            csvReader = csv.reader(csvFile)
        for row in csvReader:
            line_no = csvReader.line_num
            row_result = self.decodeCsv.get_column_name_index(line_no, row)
            if row_result == False:
                continue
            if row_result == True:
                csvFile.close()
                return row
        csvFile.close()

    def get_param_row(self, args):
        try:
            csvFile = file(self.filePath, 'rb')
            csvReader = csv.reader(csvFile)
            for row in csvReader:
                break
            csvFile = file(self.filePath, 'rb')
            csvReader = csv.reader(csvFile)
        except Exception:
            csvFile = file(self.filePath, 'rU')
            csvReader = csv.reader(csvFile)
        param_row = {}
        for row in csvReader:
            line_no = csvReader.line_num
            row_result = self.decodeCsv.get_param_row(line_no, row)
            if row_result == "Continue":
                continue
            if row_result == "UL":
                param_row[0] = (','.join(row)).split(',')
            if row_result == "LL":
                param_row[1] = (','.join(row)).split(',')
            if row_result == "MU":
                param_row[2] = (','.join(row)).split(',')
            if row_result == "Stop":
                csvFile.close()
                return param_row
        csvFile.close()

    def print_data_for_script_test(self, args):
        self.get_search_keys(args)
        self.get_attribute_keys(args)
        row = self.get_column_row(args)
        parameterStr = ','.join(row)
        parameters = parameterStr.split(',')
        params_len = len(parameters)
        column_col = []
        counts = 0
        generate_no = 1
        for i in range(0, params_len):
            if not parameters[i] in self.search_keys:
                if not parameters[i] in self.attribute_keys:
                    if len(parameters[i]) > 0 :
                        column_col.append({"i": i, "n": parameters[i]})
                    else:
                        column_col.append({"i": i, "n": ("AUTO GENERATOR NAME_" + str(generate_no))})
                        generate_no += 1
                    counts += 1
                    if counts >= int(args[6]):
                        break
        self.get_param_keys(args)
        column_col_len = len(column_col)
        for i in range(0, column_col_len):
            column_col[i]["params"] = self.param_col[column_col[i]["n"]]
        try:
            csvFile = file(self.filePath, 'rb')
            csvReader = csv.reader(csvFile)
            for row in csvReader:
                break
            csvFile = file(self.filePath, 'rb')
            csvReader = csv.reader(csvFile)
        except Exception:
            csvFile = file(self.filePath, 'rU')
            csvReader = csv.reader(csvFile)
        counts = 0
        for row in csvReader:
            line_no = csvReader.line_num
            row_result = self.decodeCsv.get_data_row(line_no, row)
            if row_result == True:
                parameterStr = ','.join(row)
                parameters = parameterStr.split(',')
                for i in range(0, column_col_len):
                    column_col[i][("data" + str(counts))] = parameters[column_col[i]["i"]]
                counts += 1
                if counts >= int(args[5]):
                    break
        print json.dumps(self.search_keys)
        print json.dumps(self.attribute_keys)
        for i in range(0, column_col_len):
            print json.dumps(column_col[i])

    def print_data_by_file(self, args):
        self.get_search_keys(args)
        self.get_param_keys(args)
        self.get_attribute_keys(args)
        txtFile = open(args[5])
        target_names = []
        for lines in txtFile.readlines():
            target_names.append(lines[:-1])
        target_col = []
        search_col_len = len(self.search_col)
        for i in range(0, search_col_len):
            target_col.append(self.search_col[i])
        attribute_col_len = len(self.attribute_col)
        for i in range(attribute_col_len):
            target_col.append(self.attribute_col[i])
        self_column_len = len(self.column_col)
        for i in range(0, self_column_len):
            if self.column_col[i]["n"] in target_names:
                target_col.append(self.column_col[i])
        target_col_len = len(target_col)
        try:
            csvFile = file(self.filePath, 'rb')
            csvReader = csv.reader(csvFile)
            for row in csvReader:
                break
            csvFile = file(self.filePath, 'rb')
            csvReader = csv.reader(csvFile)
        except Exception:
            csvFile = file(self.filePath, 'rU')
            csvReader = csv.reader(csvFile)
        for row in csvReader:
            line_no = csvReader.line_num
            row_result = self.decodeCsv.get_data_row(line_no, row)
            if row_result == True:
                data = (','.join(row)).split(',')
                data_row = OrderedDict({})
                data_len = len(data)
                for i in range(0, target_col_len):
                    data_row[target_col[i]["n"]] = data[target_col[i]["i"]]
                print json.dumps(data_row)
        csvFile.close()


def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
    return False


def main():
    print os.getpid()
    # arg = ["", "C:\Users\dmsoft\Desktop", "UserScript", "C:\Users\dmsoft\Desktop\\aa - 2.csv",
    #        "print_data_by_names", "AUTO GENERATOR NAME_1"]
    arg = sys.argv
    sys.path.append(arg[1])
    exec "import " + arg[2] + " as DataFormatScript"
    dataClass = DataFormatScript.DecodeCsvDemo()
    data = DataImportDemo(dataClass, arg[3])
    # if os.name == 'nt':
    #     data = DataImportDemo(dataClass, arg[3])
    # else:
    #     data = DataImportDemo(dataClass, arg[3][1:-1])
    eval("data." + arg[4])(arg)


main()